package com.xmb.wpclient;

import com.xmb.wpclient.config.DataBaseConfig;
import com.xmb.wpclient.entity.U8DatabaseConfig;
import com.xmb.wpclient.service.IU8DatabaseConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.sql.DriverManager;
import java.util.List;

@Component
@Slf4j
public class StartService implements ApplicationRunner {

    @Autowired
    private IU8DatabaseConfigService iU8DatabaseConfigService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<U8DatabaseConfig> dataconfigs = iU8DatabaseConfigService.list();
        if(dataconfigs.size() != 1){
            log.error("账套连接信息为空。");
            return;
        }
        U8DatabaseConfig config = dataconfigs.get(0);
        try {
            // 加载MySQL驱动程序
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            // 创建连接
            String url = "jdbc:sqlserver://"+config.getIp()+":"+config.getPort()+";Databasename="+config.getDataBase();
            String username = config.getUser();
            String password = config.getPassword();
            DataBaseConfig.connection = DriverManager.getConnection(url, username, password);
        }catch (Exception e){
            e.printStackTrace();
            log.error("账套数据库连接失败。");
        }
        log.info("账套已连接，当前账套："+config.getDataBase());
    }
}
